﻿/*
 * 作者: 谢中涞,博客园:http://www.cnblogs.com/xie-zhonglai
 * 欢迎转载,但请保留出处
 * */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Liya.Crm.Core
{
    /// <summary>
    /// 表示一组单一逻辑的查询表达式 全为And 或者全为Or
    /// </summary>
    public sealed class SingleLogicEFExpression<T> : EFExpression<T> where T : class
    {
        private ELogicType logicType;
        private IList<Expression> expressionList;      

        /// <summary>
        /// 添加一个条件
        /// </summary>
        /// <param name="exp"></param>
        public void AddExpression(Expression exp)
        {
            if (exp != null)
            {
                expressionList.Add(exp);
                _Expression = null;
            }
        }

        /// <summary>
        /// 构建新的一组单一逻辑的查询表达式
        /// </summary>
        /// <param name="logicType">逻辑类型</param>
        public SingleLogicEFExpression(ELogicType logicType)
        {
            this.logicType = logicType;
            expressionList = new List<Expression>();
        }

        public override Expression<Func<T, bool>> GetExpression()
        {
            if (this.expressionList.Count == 0)
            {
                return (Expression<Func<T, bool>>)(f => true);
            }

            return Expression.Lambda<Func<T, bool>>(Expression, this.Parameters);
        }

        internal override Expression Expression
        {
            get
            {
                if (_Expression == null)
                {
                    switch (logicType)
                    {
                        case ELogicType.And: _Expression = this.expressionList.Aggregate((e1, e2) => Expression.AndAlso(e1, e2));
                            break;
                        case ELogicType.Or: _Expression = this.expressionList.Aggregate((e1, e2) => Expression.OrElse(e1, e2));
                            break;
                        default:
                            break;
                    }

                }
                return _Expression;
            }
        }
    }
}
